package com.tensquare.spit.controller;

import com.tensquare.spit.domain.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/spit")
@CrossOrigin  //允许跨域访问
public class SpitController {

    @Autowired
    private SpitService spitService;

    @PostMapping("")
    public Result save(@RequestBody Spit spit){
        spitService.save(spit);
        return new Result(true, StatusCode.OK,"吐槽成功");
    }

    @GetMapping("")
    public Result findAll(){
        List<Spit> list = spitService.findAll();
        return new Result(true,StatusCode.OK,"查询成功",list);
    }

    /**
     * 根据id查询
     * @return
     */
    @GetMapping("/{spitId}")
    public Result findById(@PathVariable String spitId){
        Spit spit = spitService.findById(spitId);
        return new Result(true,StatusCode.OK,"查询成功",spit);
    }

    /**
     * 根据上层吐槽id查询吐槽数据
     * @param parentid 上级id
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/comment/{parentid}/{page}/{size}")
    public Result findByParentid(@PathVariable String parentid,@PathVariable int page,@PathVariable int size){
    //构建Pageable对象
        Pageable pageable=  PageRequest.of(page - 1, size);
        Page<Spit>pageData = spitService.findByParentid(parentid,pageable);
        return new Result(true,StatusCode.OK,"查询成功",new PageResult<Spit>(pageData.getTotalElements(),pageData.getContent()));
    }

    /**
     * 点赞功能,更新
     * @param spitId
     * @return
     */
    @PutMapping("/thumbup/{spitId}")
    public Result thumbup(@PathVariable String spitId){
        spitService.updateThumbup(spitId);
        return new Result(true,StatusCode.OK,"点赞成功");
    }
}
